
<template>
  <div class="app-container">
    <!-- 场景1：单个任务处理页面（带taskId参数时显示） -->
    <div v-if="taskId">
      <!-- 1. 任务详情（只读） -->
      <el-descriptions v-if="task" :column="2" border class="mb20">
        <el-descriptions-item label="标题">{{ task.title }}</el-descriptions-item>
        <el-descriptions-item label="内容">{{ task.description }}</el-descriptions-item>
        <el-descriptions-item label="级别">
          {{ task.level === 1 ? '一般' : task.level === 2 ? '紧急' : '特急' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">{{ showStatus(task.status) }}</el-descriptions-item>
        <el-descriptions-item label="责任人">{{ task.assigneeName || '未分配' }}</el-descriptions-item>
        <el-descriptions-item label="截止时间">{{ parseTime(task.deadline) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(task.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ task.finishTime ? parseTime(task.finishTime) : '未完成' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 2. 处理历史（仅当前任务） -->
      <el-table
        :data="logList"
        border
        stripe
        v-loading="loading"
        :empty-text="loading ? '加载中...' : '暂无处理记录'"
      >
        <el-table-column label="处理人" prop="handlerName" width="120" />
        <el-table-column label="处理内容" prop="result" />
        <el-table-column label="附件" prop="files">
          <template #default="scope">
            <span v-if="scope.row.files">
              <a
                v-for="(url, idx) in parseFiles(scope.row.files)"
                :key="idx"
                :href="url"
                target="_blank"
                class="mr-2 text-primary"
              >
                附件{{ idx + 1 }}
              </a>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" prop="handleTime" width="180" />
        <el-table-column label="处理后状态" prop="status">
          <template #default="scope">{{ showStatus(scope.row.status) }}</template>
        </el-table-column>
        <!-- 管理者可见：日志操作按钮 -->
        <el-table-column
          label="操作"
          align="center"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['emergency:log:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['emergency:log:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 3. 处理表单（仅当前责任人且任务未完成可见，逾期时禁用） -->
      <el-form
        v-if="isAssignee && !isFinished"
        ref="processForm"
        :model="form"
        :rules="rules"
        label-width="90px"
        class="mt20"
        :disabled="isOverdue"
      >
        <el-form-item label="处理内容" prop="result">
          <el-input v-model="form.result" type="textarea" rows="3" placeholder="请输入处理进度或结果" :disabled="isOverdue"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="/api/file/upload"
            :on-success="handleFileSuccess"
            :file-list="form.fileList"
            :limit="3"
            :on-exceed="(files, fileList) => $message.warning('最多上传3个附件')"
            list-type="text"
            :disabled="isOverdue"
          >
            <el-button type="primary" size="small" :disabled="isOverdue">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.complete" :disabled="isOverdue">确认任务已完成</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitProcess" :disabled="isOverdue">提交处理</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 场景2：管理者日志管理页面（无taskId参数时显示） -->
    <div v-else>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="关联任务ID" prop="taskId">
          <el-input
            v-model="queryParams.taskId"
            placeholder="请输入关联任务ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="处理人ID" prop="handlerId">
          <el-input
            v-model="queryParams.handlerId"
            placeholder="请输入处理人ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker clearable
                          v-model="queryParams.handleTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择处理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" clearable placeholder="请选择状态">
            <el-option label="进行中" value="1"></el-option>
            <el-option label="已完成" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-if="isAdmin"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['emergency:log:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['emergency:log:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['emergency:log:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['emergency:log:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="logList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" width="80" />
        <el-table-column label="关联任务ID" align="center" prop="taskId" />
        <el-table-column label="处理人" align="center" prop="handlerName" />
        <el-table-column label="处理时间" align="center" prop="handleTime" width="180">
          <template #default="scope">{{ parseTime(scope.row.handleTime) }}</template>
        </el-table-column>
        <el-table-column label="处理内容" align="center" prop="result" />
        <el-table-column label="附件" align="center" prop="files">
          <template #default="scope">
            <span v-if="scope.row.files">
              <a
                v-for="(url, idx) in parseFiles(scope.row.files)"
                :key="idx"
                :href="url"
                target="_blank"
                class="mr-2 text-primary"
              >附件{{ idx + 1 }}</a>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <span v-if="scope.row.status === 3" style="color: #f56c6c; font-weight: bold;">逾期</span>
            <span v-else>{{ showStatus(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['emergency:log:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['emergency:log:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 管理者：新增/修改日志对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="manageForm" :model="manageForm" :rules="manageRules" label-width="80px">
        <el-form-item label="关联任务ID" prop="taskId">
          <el-input v-model="manageForm.taskId" placeholder="请输入关联任务ID" />
        </el-form-item>
        <el-form-item label="处理人ID" prop="handlerId">
          <el-input v-model="manageForm.handlerId" placeholder="请输入处理人ID" />
        </el-form-item>
        <el-form-item label="处理人名称" prop="handlerName">
          <el-input v-model="manageForm.handlerName" placeholder="请输入处理人名称" />
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker clearable
                          v-model="manageForm.handleTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择处理时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="处理内容" prop="result">
          <el-input v-model="manageForm.result" type="textarea" placeholder="请输入处理内容" />
        </el-form-item>
        <el-form-item label="处理附件">
          <el-upload
            action="/api/file/upload"
            :on-success="handleManageFileSuccess"
            :file-list="manageForm.fileList"
            :limit="3"
            list-type="text"
          >
            <el-button type="primary" size="small">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="manageForm.status" placeholder="请选择处理后状态">
            <el-option label="进行中" value="1"></el-option>
            <el-option label="已完成" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitManageForm">确 定</el-button>
        <el-button @click="cancelManage">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTask } from '@/api/emergency/task'
import { listLog, addLog, getLog, delLog, updateLog } from '@/api/emergency/log'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import RightToolbar from '@/components/RightToolbar'

export default {
  name: "Log",
  components: { Pagination, RightToolbar },
  data() {
    return {
      // 路由参数：任务ID（有则显示单个任务处理页，无则显示管理页）
      taskId: this.$route.query.taskId,
      // 当前任务详情（单个任务场景用）
      task: null,
      // 日志列表（通用）
      logList: [],
      // 加载状态
      loading: false,
      // 总条数（管理页用）
      total: 0,
      // 选中数组（管理页用）
      ids: [],
      // 非单个禁用（管理页用）
      single: true,
      // 非多个禁用（管理页用）
      multiple: true,
      // 显示搜索条件（管理页用）
      showSearch: true,
      // 新增/修改对话框（管理页用）
      open: false,
      title: "",
      // 管理页查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        handlerId: null,
        handleTime: null,
        status: null
      },
      // 单个任务处理表单（用户用）
      form: {
        taskId: null,
        result: '',
        files: '', // 附件URL数组JSON字符串
        fileList: [], // 上传组件文件列表
        complete: false
      },
      // 处理表单校验规则
      rules: {
        result: [{ required: true, message: '请输入处理内容', trigger: 'blur' }]
      },
      // 管理者新增/修改表单
      manageForm: {
        id: null,
        taskId: null,
        handlerId: null,
        handlerName: null,
        handleTime: null,
        result: null,
        files: '', // 附件URL数组JSON字符串
        fileList: [], // 上传组件文件列表
        status: 1
      },
      // 管理者表单校验规则
      manageRules: {
        taskId: [{ required: true, message: '关联任务ID不能为空', trigger: 'blur' }],
        handlerId: [{ required: true, message: '处理人ID不能为空', trigger: 'blur' }],
        handlerName: [{ required: true, message: '处理人名称不能为空', trigger: 'blur' }],
        handleTime: [{ required: true, message: '处理时间不能为空', trigger: 'blur' }],
        result: [{ required: true, message: '处理内容不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    // 当前登录用户ID
    userId() {
      return this.$store.state.user.id
    },
    // 是否为管理员
    isAdmin() {
      return this.$store.state.user.roles && this.$store.state.user.roles.some(r => r === 'admin' || r === '管理员')
    },
    // 是否为当前任务的责任人（单个任务场景用）
    isAssignee() {
      return this.task && this.userId === this.task.assigneeId
    },
    // 任务是否已完成（单个任务场景用）
    isFinished() {
      return this.task && this.task.status === 2
    },
    isOverdue() {
      return this.task && this.task.status === 3;
    }
  },
  watch: {
    // 监听路由参数变化，重新加载数据
    '$route.query.taskId'(newVal) {
      this.taskId = newVal
      this.initPage()
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    // 初始化页面（根据是否有taskId加载不同数据）
    initPage() {
      if (this.taskId) {
        // 单个任务处理场景
        this.loadTask()
        this.loadTaskLogs()
      } else {
        // 管理者日志管理场景
        this.getList()
      }
    },

    // ---------------------- 单个任务处理场景方法 ----------------------
    // 加载任务详情
    loadTask() {
      this.loading = true
      getTask(this.taskId).then(res => {
        this.task = res.data
        this.form.taskId = this.taskId
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取任务详情失败')
      })
    },
    // 加载单个任务的处理历史
    loadTaskLogs() {
      this.loading = true
      listLog({ taskId: this.taskId }).then(res => {
        this.logList = res.rows.sort((a, b) => new Date(b.handleTime) - new Date(a.handleTime)) // 按时间倒序
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取处理历史失败')
      })
    },
    // 处理表单附件上传成功
    handleFileSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.fileList = fileList
        this.form.files = JSON.stringify(fileList.map(f => f.response.url))
      } else {
        this.$message.error('附件上传失败')
      }
    },
    // 提交处理内容
    submitProcess() {
      this.$refs.processForm.validate(valid => {
        if (!valid) return
        this.loading = true
        const logData = {
          taskId: this.form.taskId,
          handlerId: this.userId,
          handlerName: this.$store.state.user.name, // 当前用户名称
          result: this.form.result,
          files: this.form.files,
          status: this.form.complete ? 2 : 1
        }
        addLog(logData).then(() => {
          this.$message.success('处理成功')
          // 重置表单
          this.form.result = ''
          this.form.complete = false
          this.form.fileList = []
          this.form.files = ''
          // 刷新数据
          this.loadTask()
          this.loadTaskLogs()
        }).catch(() => {
          this.$message.error('处理失败')
        }).finally(() => {
          this.loading = false
        })
      })
    },

    // ---------------------- 管理者日志管理场景方法 ----------------------
    // 查询日志列表
    getList() {
      this.loading = true
      listLog(this.queryParams).then(response => {
        this.logList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置搜索
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 新增按钮操作
    handleAdd() {
      this.resetManageForm();
      this.open = true;
      this.title = "添加应急任务处理日志";
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.resetManageForm();
      const id = row.id || this.ids[0];
      getLog(id).then(response => {
        const data = response.data;
        this.manageForm = {
          ...data,
          fileList: this.parseFiles(data.files).map(url => ({ url })),
          handleTime: new Date(data.handleTime)
        };
        this.open = true;
        this.title = "修改应急任务处理日志";
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的日志？').then(() => {
        return delLog(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    // 导出日志
    handleExport() {
      this.download('emergency/log/export', { ...this.queryParams }, `log_${new Date().getTime()}.xlsx`)
    },
    // 管理表单附件上传成功
    handleManageFileSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.manageForm.fileList = fileList
      } else {
        this.$message.error('附件上传失败')
      }
    },
    // 重置管理表单
    resetManageForm() {
      this.manageForm = {
        id: null,
        taskId: null,
        handlerId: null,
        handlerName: null,
        handleTime: new Date(),
        result: '',
        files: '',
        fileList: [],
        status: 1
      }
      this.resetForm("manageForm")
    },
    // 取消管理表单
    cancelManage() {
      this.open = false
      this.resetManageForm()
    },
    submitManageForm() {
      this.$refs.manageForm.validate(valid => {
        if (!valid) return;
        this.loading = true;
        const data = {
          ...this.manageForm,
          files: JSON.stringify(this.manageForm.fileList.map(f => f.url))
        };
        const api = data.id ? updateLog : addLog;
        api(data).then(() => {
          this.$message.success(data.id ? '修改成功' : '新增成功');
          this.open = false;
          this.getList();
        }).catch(() => {
          this.$message.error(data.id ? '修改失败' : '新增失败');
        }).finally(() => {
          this.loading = false;
        });
      });
    },

    // ---------------------- 通用方法 ----------------------
    // 状态显示转换
    showStatus(status) {
      const map = { 0: '待处理', 1: '进行中', 2: '已完成', 3: '逾期' }
      return map[status] || '未知'
    },
    // 解析附件URL（JSON字符串转数组）
    parseFiles(files) {
      try {
        return files ? JSON.parse(files) : []
      } catch (e) {
        return []
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName]?.resetFields()
    },
    // 时间格式化
    parseTime(time, format = 'yyyy-MM-dd HH:mm:ss') {
      if (!time) return '';
      let date;
      if (typeof time === 'string' && time.indexOf('-') > -1 && time.indexOf(':') > -1) {
        date = new Date(time.replace(/-/g, '/'));
      } else {
        date = new Date(time);
      }
      if (isNaN(date.getTime())) return time;
      const y = date.getFullYear();
      const m = (date.getMonth() + 1).toString().padStart(2, '0');
      const d = date.getDate().toString().padStart(2, '0');
      const h = date.getHours().toString().padStart(2, '0');
      const min = date.getMinutes().toString().padStart(2, '0');
      const s = date.getSeconds().toString().padStart(2, '0');
      if (format === 'yyyy-MM-dd') {
        return `${y}-${m}-${d}`;
      }
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    }
  }
}
</script>
